#include "D2DRender.h"


D2DRender::D2DRender(IDXGISwapChain * const sc, IDXGIDevice * const device)
{
	this->swapChain = sc;
	swapChain->AddRef();

	this->dxgiDevice = device;
	dxgiDevice->AddRef();
	Init();
}


D2DRender::~D2DRender(void)
{
	ReleaseCOM(d2Factory);
	ReleaseCOM(dWriteFactory);
	ReleaseCOM(wicFactory);

	ReleaseCOM(swapChain);
	ReleaseCOM(dxgiDevice);
}

void D2DRender::Init()
{
	//D2 factory
	HR(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2Factory));

	//WIC factory
	HR(CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, reinterpret_cast<void**>(&wicFactory)));

	//DWrite factory
	HR(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(dWriteFactory), reinterpret_cast<IUnknown**>(&dWriteFactory)));

	//Create render target
	IDXGISurface * backBuffer;
	HR(swapChain->GetBuffer(0, __uuidof(IDXGISurface), reinterpret_cast<void**>(&backBuffer)));

	float dpiX, dpiY;
	d2Factory->GetDesktopDpi(&dpiX, &dpiY);

	D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT,
		D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED),
		dpiX,
		dpiY);

	HR(d2Factory->CreateDxgiSurfaceRenderTarget(backBuffer, &props, &backBufferRT));

	ReleaseCOM(backBuffer);

}

void D2DRender::Update()
{

}

void D2DRender::Draw()
{
	//Test
	ID2D1SolidColorBrush * brush;
	backBufferRT->CreateSolidColorBrush(D2D1::ColorF(1.0f, 0.0f, 0.0f, 1.0f), &brush);

	IDWriteTextFormat * format;

	dWriteFactory->CreateTextFormat(L"Verdana", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 36.0f, L"", &format);

	backBufferRT->BeginDraw();
	
	backBufferRT->SetTransform(D2D1::Matrix3x2F::Translation((float)GD::_ED.windowWidth / 2, (float)GD::_ED.windowHeight / 2 ));

	backBufferRT->DrawText(L"Hello World", 11, format, D2D1::RectF(0.0f, 0.0f, (float)GD::_ED.windowWidth, (float)GD::_ED.windowHeight), brush);

	backBufferRT->SetTransform(D2D1::IdentityMatrix());

	backBufferRT->DrawEllipse(D2D1::Ellipse(D2D1::Point2F(50.0f, 100.0f), 10.0f, 30.0f), brush);

	backBufferRT->EndDraw();

	ReleaseCOM(brush);
}

void D2DRender::OnResize()
{
	//Create render target
	IDXGISurface * backBuffer;
	HR(swapChain->GetBuffer(0, __uuidof(IDXGISurface), reinterpret_cast<void**>(&backBuffer)));

	float dpiX, dpiY;
	d2Factory->GetDesktopDpi(&dpiX, &dpiY);

	D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT,
		D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED),
		dpiX,
		dpiY);

	HR(d2Factory->CreateDxgiSurfaceRenderTarget(backBuffer, &props, &backBufferRT));

	ReleaseCOM(backBuffer);
}

void D2DRender::ReleaseResizedResources()
{
	ReleaseCOM(backBufferRT);
}